package com.sparsearr.datastructures.ztr.search;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/6/2 20:18
 * @Description: 插值查找算法
 * @Version: 1.0
 */

public class InsertValueSearch {
    private static final Logger logger = LogManager.getLogger(InsertValueSearch.class);
    static int count = 0;

    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < 100; i++) {
            arr[i] = i + 1;
        }

        int index = insertValueSearch(arr, 0, arr.length - 1, 1);
        logger.info("index = {}", index);
    }

    /**
     * 插值查找算法
     * 说明: 数组必须是有序的
     *
     * @param arr     数组
     * @param left    左边索引
     * @param right   右边索引
     * @param findVal 查找的值
     * @return 如果找到，就返回对应的下标，如果没有找到，就返回-1
     */
    public static int insertValueSearch(int[] arr, int left, int right, int findVal) {
        count++;
        System.out.println("第" + count + "次查找");
        // 注意：findVal < arr[0] || findVal > arr[arr.length - 1] 必须需要，否则得到的可能越界
        if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
            return -1;
        }
        // 求出mid
        int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
        int midVal = arr[mid];
        // 向右递归
        if (findVal > midVal) {
            return insertValueSearch(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) {
            return insertValueSearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

}
